<?php
/**
-------------------------
GNU GPL COPYRIGHT NOTICES
-------------------------
This file is part of FlexicaCMS.

FlexicaCMS is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

FlexicaCMS is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with FlexicaCMS.  If not, see <http://www.gnu.org/licenses/>.*/

/**
 * $Id$
 *
 * @author FlexicaCMS team <contact@flexicacms.com>
 * @link http://www.flexicacms.com/
 * @copyright Copyright &copy; 2009-2010 Gia Han Online Solutions Ltd.
 * @license http://www.flexicacms.com/license.html
 */
class ForeignKeyDropDownList extends CInputWidget
{
    public $criteria;
    public $referenceModel;
    public $referenceTextField; // string or array
    public $promptText = null;
    public $separator = ' '; // apply when $referenceTextField is array 
    
    public function run () {
        $refModel = new $this->referenceModel;
        if (empty($this->criteria)) $this->criteria = new CDbCriteria();
        
        $result = $refModel->findAll($this->criteria);
        
        if(is_array($this->referenceTextField)) {
        	if($result) {
		        foreach($result as $item) {
		        	$textField = array();
		        	foreach($this->referenceTextField as $field) array_push($textField, $item->{$field});
		        	 
		    		$data[$item->{$refModel->TableSchema->primaryKey}] = implode($this->separator, $textField);    		
		        }	
        	}
        } else {
        	$data = CHtml::listData($result, $refModel->TableSchema->primaryKey, $this->referenceTextField);
        }

        if ($this->promptText !== null)
            $this->htmlOptions['prompt'] = $this->promptText;
            
        echo CHtml::activeDropDownList($this->model, $this->attribute, $data, $this->htmlOptions);
    }
}
?>
